﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Configuration.Client;
using CPPEI.Coolzon.ServiceProxy.UpdateServiceRef;
using CPPEI.Coolzon.Theme;
using CPPEI.WPF.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.ConsoleApp
{
    /// <summary>
    /// SplashWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SplashWindow : Window
    {
        private Thread _thread;
        private UpdateServiceClient _client;
        private AppInfo _appInfo;
        private ServiceConfig _serviceConfig;
        public bool IsContinueRunning { get; private set; }
        private bool _isCheckVersion;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="IsCheckVersion">true检查应用程序更新,false不检查程序更新</param>
        /// <param name="appInfo"></param>
        /// <param name="serviceConfig"></param>
        public SplashWindow(bool IsCheckVersion, AppInfo appInfo, ServiceConfig serviceConfig)
        {
            InitializeComponent();
            _isCheckVersion = IsCheckVersion;
            this._appInfo = appInfo;
            this._serviceConfig = serviceConfig;

            //版本信息
            this._versionInfo.Text = "V" + WEITSM.Console.App.AppInfo.Version.ToString(3);
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            if (_thread == null)
            {
                _client = CreateUpdateServiceClient();
                _thread = new Thread(Running);
                _thread.Start();
            }
        }

        private void Running()
        {
            IsContinueRunning = true;

            this.Dispatcher.Invoke(() =>
            {
                tbMessage.Text = "检测更新中……";
            });

            if (_isCheckVersion)
            { 
                ValidateUpdate();
            }

            //if (IsContinueRunning)
            //{
            //    this.Dispatcher.Invoke(() =>
            //    {
            //        tbMessage.Text = "初始化主题配置……";
            //    });
            //    InitThemeConfig();
            //}

            if (IsContinueRunning)
            {
                this.Dispatcher.Invoke(() =>
                {
                    this.DialogResult = IsContinueRunning;
                });
            }
        }

        /// <summary>
        /// 初始化主题配置信息
        /// </summary>
        private void InitThemeConfig()
        {
            //try
            //{
            //    ThemeManager.Init(AppDomain.CurrentDomain.BaseDirectory + "Config\\Theme.xml");
            //}
            //catch (Exception ex)
            //{
            //    this.Dispatcher.Invoke(() =>
            //    {
            //        IsContinueRunning = false;

            //        MessageBox.Show(ex.Message + "\n\n程序退出。", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
            //        XApplication.XCurrent.Shutdown();
            //    });
            //}
        }

        /// <summary>
        /// 获取更新信息
        /// </summary>
        private void ValidateUpdate()
        {
           // CPPEI.Coolzon.ServiceProxy.UpdateServiceRef.UpdateSchedule updateSchedule = null;
            CPPEI.Coolzon.ServiceProxy.UpdateServiceRef.CheckVersionResult checkVersionResult = null;

            try
            {

               checkVersionResult = _client.CheckVersion(_appInfo.Product, _appInfo.Type, _appInfo.Version.ToString(4));
                
               //updateSchedule = _client.GetUpdateSchedule(_appInfo.Product,_appInfo.Type, _appInfo.Version.ToString(4));
            }
            catch (Exception ex)
            {
                // 获取更新信息出错
                Common.Logger.ErrorToTag("UpdatingProcess", "获取更新信息出错,ex:{0}", ex);
                return;
            }

            if (checkVersionResult != null)
            {
                if (checkVersionResult.HasIncrementalPatch || checkVersionResult.HasFullPatch)
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        //判断是否为必须更新
                        if (checkVersionResult.IsNecessary)
                        {
                            IsContinueRunning = false;
                            XApplication.XCurrent.StartUpdateAppAndShutdown();
                        }
                        else
                        {
                            if (MessageBox.Show("已检测到有更新，是否下载更新", "更新提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                            {
                                IsContinueRunning = false;
                                XApplication.XCurrent.StartUpdateAppAndShutdown();
                            }
                        }
                    });
                }
                else
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        tbMessage.Text = "获取更新出错！";
                    });
                }
            }
        }

        /// <summary>
        /// 创建访问更新服务器的客户端对象
        /// </summary>
        /// <param name="hostConfig"></param>
        /// <returns></returns>
        private UpdateServiceClient CreateUpdateServiceClient()
        {
            System.ServiceModel.Channels.Binding tcpBinding = new NetTcpBinding();
            (tcpBinding as NetTcpBinding).Security.Mode = SecurityMode.None;
            (tcpBinding as NetTcpBinding).MaxBufferSize = 1024 * 1024 * 1024;
            (tcpBinding as NetTcpBinding).MaxReceivedMessageSize = 1024 * 1024 * 1024;
            EndpointAddress address = new EndpointAddress(string.Format("net.tcp://{0}:{1}/{2}/", _serviceConfig.IP, _serviceConfig.Port, _serviceConfig.Name));

            UpdateServiceClient updateServiceClient = new UpdateServiceClient(tcpBinding, address);
            return updateServiceClient;
        }

        /// <summary>
        /// 拖动窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Grid_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
    }
}
